<template>
  <div id="personalModify">
    <!-- pc -->
    <div class="wrapper">
      <!-- 返回按钮 -->
      <div class="back_part">
        <div class="back_btn" @click="goBack">
          <img src="@/assets/images/pc_black/auth/back.png" />
          <span>返回</span>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="textContent">
        <!-- 标题 -->
        <div class="contentTitle">修改资料</div>

        <!-- 内容 -->
        <div class="contentBody">
          <div class="form">
            <!-- 名称 -->
            <div class="nicknameInput">
              <span class="fontWrapper"><i>*</i>名称</span>
              <input
                class="formIpt"
                v-model.trim="formData.nickname"
                placeholder="请输入名称"
                maxlength="15"
                onkeyup="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\.\,\?\<\>\。\，\-\——\=\;\@\！\!\+\$\_]/g,'')"
                onpaste="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\.\,\?\<\>\。\，\-\——\=\;\@\！\!\+\$\_]/g,'')"
                oncontextmenu="value=value.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\.\,\?\<\>\。\，\-\——\=\;\@\！\!\+\$\_]/g,'')"
              />
            </div>
            <p class="tip">请输入不超过15个字符的名称</p>

            <!-- 上传用户头像 -->
            <div class="avatarInput">
              <span class="fontWrapper"><i>*</i>用户头像</span>
              <img class="showAvatar" :src="showAvatar" />
            </div>
            <div class="upload_box">
              <div class="upload_box_tip">
                <img class="upload_box_img" src="@/assets/images/pc_black/center/upload.png" />
                <span class="upload_box_font">更换头像</span>
              </div>

              <FileUpload ref="fileUpload" type="input" @uploadFiles="uploadFilesData" />
            </div>
            <p class="tip">请上传格式为JPG/PNG的图片，且图片大小不超过10M</p>

            <!-- 描述 -->
            <div class="describeInput">
              <span class="fontWrapper">描述</span>
              <el-input
                class="formIpt"
                type="textarea"
                v-model="formData.description"
                placeholder="请输入内容"
                resize="none"
              ></el-input>

              <span class="limit">
                <span
                  v-if="formData.description && formData.description.length > 100"
                  class="limitOut"
                  >{{ formData.description.length }}</span
                >
                <span
                  v-else-if="formData.description && formData.description.length <= 100"
                  class="limitIn"
                  >{{ formData.description.length }}</span
                >
                <span v-else class="limitIn">0</span>/100
              </span>
            </div>
            <p class="tip">描述信息长度不超过100个字符</p>
          </div>

          <!-- 提交按钮 -->
          <el-button class="submitBtn" @click="submit">提交</el-button>
        </div>
      </div>
    </div>

    <!-- mobile -->
    <div class="mContainer">
      <ul class="mContainerUl">
        <li>
          <span>头像</span>
          <!-- <FileUpload
            class="avatarUpload"
            type="image-circle"
            :defaultCircle="userInfo.avatar"
            @uploadImage="uploadFilesData"
          /> -->
          <div class="m_showAvatar_box">
            <FileUpload
              class="avatarUpload"
              type="image-circle"
              @uploadImage="uploadFilesData"
              @click="stopdefault"
            />
            <img
              class="m_showAvatar"
              :src="
                userInfo.avatar
                  ? userInfo.avatar
                  : require('@/assets/images/mobile_black/center/avatar_default.png')
              "
            />
          </div>
        </li>
        <li @click="gotoModifyNickname">
          <span>昵称</span>
          <span>{{ userInfo.nickname || "METAUP" }}</span>
        </li>
        <li @click="gotoModifyDescription">
          <span>个人描述</span>
          <span>{{ userInfo.remark || "这个人什么也没留下" }}</span>
        </li>
        <li @click="gotoCertified">
          <span>实名认证</span>
          <div class="forthRight">
            <img
              v-if="userInfo.is_auth === 0"
              src="@/assets/images/mobile_black/center/auth_not.png"
            />
            <img v-else src="@/assets/images/mobile_black/center/auth_already.png" />
            <span v-if="userInfo.is_auth === 0">未认证</span>
            <span class="certified" v-else>已认证</span>
          </div>
        </li>
      </ul>

      <div class="exitLoginBox">
        <el-button class="exitLogin btn_grey" @click="openConfirmDialog">退出登录</el-button>
      </div>
    </div>

    <!-- confirm dialog -->
    <van-dialog
      v-model="isShowConfirmDialog"
      show-cancel-button
      cancel-button-text="取消"
      confirm-button-text="确认退出"
      confirm-button-color="#00ffb0"
      :beforeClose="defaultClose"
      @cancel="closeConfirmDialog"
      @confirm="certified"
    >
      <span>确认要退出登录吗?</span>
      <span>退出后将无法查看和购买数字藏品哦！</span>
    </van-dialog>
  </div>
</template>

<script>
import FileUpload from "@/components/FileUpload.vue";
import { updateProfileApi, uploadAvatarApi } from "@/api";
import { iscode, getWidth, reHeight } from "@/utils";
import { mapState, mapMutations, mapActions } from "vuex";
import { clearCookies } from "@/utils/cookie";

export default {
  name: "PersonalModify",
  components: { FileUpload },
  data() {
    return {
      // 表单数据
      formData: {
        nickname: "",
        avatar: "",
        description: ""
      },
      // 移动端上传文件
      fileList: [],
      showAvatar: "",
      // 是否显示确认认证谈弹窗
      isShowConfirmDialog: false
    };
  },
  computed: {
    ...mapState(["userInfo"])
  },
  mounted() {
    this.formData.nickname = this.userInfo.nickname;
    this.formData.description = this.userInfo.remark;
    this.showAvatar = this.userInfo.avatar
      ? this.userInfo.avatar
      : require("@/assets/images/mobile_black/center/avatar_default.png");

    reHeight("personalModify", this);
  },
  methods: {
    // ------ 异步相关的方法 ------
    // 保存修改
    async updateProfile(isOnlyAvatar) {
      // isOnlyAvatar: false是pc提交按钮统一修改，true是移动端点击头像之后直接修改头像
      let result = null;
      if (isOnlyAvatar) {
        // mobile
        result = await updateProfileApi({
          avatar: this.formData.avatar
        });
      } else {
        // pc
        result = await updateProfileApi({
          avatar: this.formData.avatar,
          nickname: this.formData.nickname,
          remark: this.formData.description ? this.formData.description.trim() : ""
        });
      }

      if (iscode(result)) {
        this.getUserInfo();
        this.$nextTick(() => {});

        if (!isOnlyAvatar) {
          // pc
          this.$router.push("/personalCenter");
          this.$message({
            message: "修改完成",
            iconClass: "mySuccessIcon",
            customClass: "mySuccess"
          });
        } else {
          // mobile
          this.$toast({ message: "修改完成", type: "success" });
        }
      }
    },
    // pc/mobile 拿到上传的文件
    async uploadFilesData(payload, fileSrc) {
      let isCheckOK = this.uploadFilesDataCheck(payload[0]);
      if (isCheckOK) {
        // 将文件的路径传给展示图片
        this.showAvatar = fileSrc;
        let fd = new FormData();
        fd.append("avatar", payload[0]);
        let result = await uploadAvatarApi(fd);
        if (iscode(result)) {
          this.formData.avatar = result.result.avatar;
          // 当移动端时直接调用保存修改
          if (getWidth() <= 768) {
            // false是通过pc提交按钮统一修改，true是通过移动端点击头像之后直接修改
            this.updateProfile(true);
          }
        }
      } else {
        this.$nextTick(() => {
          if (getWidth() > 768) {
            this.$refs.fileUpload.$children[0].clearInput();
          }
        });
      }
    },

    // ------ 功能性方法 ------
    // store里的方法
    ...mapMutations(["clearUserInfo"]),
    // 获取用户信息（用于认证之后更新vuex里的userInfo数据）
    ...mapActions(["getUserInfo"]),

    // pc检查上传的文件是否为符合大小的图片（参数为文件类型，符合结果返回ture，不符合返回false）
    uploadFilesDataCheck(file) {
      // 检查文件拓展名是否符合jpg、png两种格式
      var aa = file.name.toLowerCase().split(".");
      if (
        aa[aa.length - 1] === "png" ||
        aa[aa.length - 1] === "jpg" ||
        aa[aa.length - 1] === "jpeg"
      ) {
        // 检查文件大小是否符合不超过10M
        var imagSize = file.size;
        if (imagSize <= 1024 * 1024 * 10) {
          return true;
        } else {
          if (getWidth() <= 768) {
            this.$toast("图片大小不超过10M");
          } else {
            this.$message({
              message: "图片大小不超过10M",
              iconClass: "myWarningIcon",
              customClass: "myWarning"
            });
          }
          return false;
        }
      } else {
        if (getWidth() <= 768) {
          this.$toast("请上传格式为JPG/PNG的图片");
        } else {
          this.$message({
            message: "请上传格式为JPG/PNG的图片",
            iconClass: "myWarningIcon",
            customClass: "myWarning"
          });
        }
        return false;
      }
    },
    // 表单按钮触发提交
    submit() {
      if (!this.formData.nickname) {
        this.$message({
          message: "名称不能为空",
          iconClass: "myErrorIcon",
          customClass: "myError"
        });
        return;
      } else if (this.formData.nickname.length > 10) {
        this.$message({
          message: "名称不能超过10个字符",
          iconClass: "myErrorIcon",
          customClass: "myError"
        });
        return;
      } else if (this.formData.description && this.formData.description.length > 100) {
        this.$message({
          message: "描述信息长度不能超过100个字符",
          iconClass: "myErrorIcon",
          customClass: "myError"
        });
        return;
      }
      // false是通过pc提交按钮统一修改，true是通过移动端点击头像之后直接修改
      this.updateProfile(false);
    },
    // 退出登录
    exitLogin() {
      window.localStorage.removeItem("isLogin");
      window.localStorage.removeItem("phoneFirstLogin");
      window.localStorage.removeItem("pcFirstLogin");
      window.localStorage.removeItem("isJump");
      window.localStorage.removeItem("fragInfo");
      this.$store.commit("closeNoticeDialog");
      this.$router.push("/login");
      clearCookies();
      window.localStorage.removeItem("token");

      // localStorage.clear();

      this.clearUserInfo();
      this.$toast("账号已退出");
    },
    // 确认创建
    certified() {
      this.closeConfirmDialog();
      const that = this;

      // 加载
      this.$toast.loading({
        className: "loading_style",
        message: "正在加载",
        forbidClick: true,
        duration: 2000,
        onClose() {
          that.exitLogin();
        }
      });
    },
    // 阻止dialog默认的关闭事件
    defaultClose(action, done) {
      done(false);
    },
    // 打开确认退出弹窗
    openConfirmDialog() {
      this.isShowConfirmDialog = true;
    },
    // 关闭确认退出弹窗
    closeConfirmDialog() {
      this.isShowConfirmDialog = false;
    },
    //屏蔽默认键盘弹出
    stopdefault() {
      document.activeElement.blur();
    },

    // ----- 跳转相关的方法 -----
    // 返回按钮触发返回到上个界面
    goBack() {
      this.$router.go(-1);
    },
    gotoModifyNickname() {
      this.$router.push("/personalNicknameModify");
    },
    gotoModifyDescription() {
      this.$router.push("/personalDescriptionModify");
    },
    gotoCertified() {
      if (this.userInfo.is_auth === 1) {
        this.$toast({
          className: "authentication_already",
          message: "身份已认证",
          duration: 2000
        });
      } else {
        this.$router.push("/authentication");
      }
    }
  }
};
</script>

<style lang="less" scoped>
#personalModify {
  width: 100%;
  min-height: 903px;

  // 隐藏移动端
  .mContainer {
    display: none;
  }

  // 版心
  .wrapper {
    width: 1200px;
    margin: 0 auto;

    // -退回按钮div
    .back_part {
      width: 100%;
      padding-top: 20px;

      .back_btn {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 104px;
        height: 30px;
        border: none;
        background: none;
        background-image: url("../../assets/images/personalCenter/btn.png");
        background-position: center center;
        background-size: 100% 100%;
        cursor: pointer;

        img {
          width: 20px;
          height: 6px;
        }

        span {
          font-size: 12px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #ffffff;
          line-height: 12px;
          margin-left: 10px;
        }
      }
    }

    // -内容总框
    .textContent {
      margin-top: 30px;

      // 内容标题样式
      .contentTitle {
        font-size: 18px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        color: #ffffff;
        line-height: 18px;
      }

      // 具体内容样式
      .contentBody {
        margin-top: 30px;
        display: flex;
        flex-direction: column;

        .form {
          // 星号
          i {
            color: #f24038;
          }
          // 左侧提示字（名称...）
          .fontWrapper {
            min-width: 72px;
            font-size: 16px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            line-height: 16px;
            color: #ffffff;
            text-align: right;
            margin-right: 20px;
          }

          // 右侧提示字（输入不超过...）
          .tip {
            font-size: 12px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999999;
            line-height: 12px;
            margin-top: 15px;
            margin-left: 90px;
          }

          // 名称
          .nicknameInput {
            display: flex;
            align-items: center;

            .formIpt {
              width: 300px;
              height: 42px;
              background: #1e2020;
              border: 1px solid #444444;
              padding-left: 15px;
              font-size: 14px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              color: #ffffff;
              line-height: 14px;
            }

            ::-webkit-input-placeholder {
              /* WebKit, Blink, Edge */
              color: #555555 !important;
            }
            :-moz-placeholder {
              /* Mozilla Firefox 4 to 18 */
              color: #555555 !important;
            }
            ::-moz-placeholder {
              /* Mozilla Firefox 19+ */
              color: #555555 !important;
            }
            :-ms-input-placeholder {
              /* Internet Explorer 10-11 */
              color: #555555 !important;
            }
          }

          // 上传头像
          .avatarInput {
            display: flex;
            align-items: center;
            margin-top: 30px;

            .showAvatar {
              width: 80px;
              height: 80px;
              border-radius: 50%;
            }
          }
          .upload_box {
            position: relative;
            width: 110px;
            height: 36px;
            border: 1px solid #00ffb0;
            margin: 20px 0 0 90px;

            span {
              height: 100%;
            }
            /deep/.md-field,
            /deep/.md-input {
              margin: 0;
              padding: 0;
              width: 100%;
              height: 100%;
              opacity: 0;
              cursor: pointer;
            }
            /deep/.md-field:before,
            /deep/.md-field:after {
              display: none;
            }

            .upload_box_tip {
              position: absolute;
              top: 0;
              left: 0;
              display: flex;
              justify-content: center;
              align-items: center;
              height: 100%;
              width: 100%;
              padding: 11px 0;

              .upload_box_img {
                width: 14px;
                height: 14px;
                padding: 0;
                margin: 0;
                // margin-left: 15px;
              }

              .upload_box_font {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                line-height: 14px;
                color: #00ffb0;
                word-break: keep-all;
                margin-left: 10px;
              }
            }
          }

          // 描述
          .describeInput {
            position: relative;
            display: flex;
            margin-top: 30px;

            .formIpt {
              width: 500px;
              height: 220px;
              border: 1px solid #444444;
              padding: 15px 15px 42px 15px;

              /deep/.el-textarea {
                width: 100%;
                height: 100%;
                background: #1e2020;
              }
              /deep/.el-textarea__inner {
                width: 100%;
                height: 100%;
                background: none;
                border: none;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #ffffff;
                line-height: 22px;
                padding: 0;
                padding-bottom: 42px;
              }
              /deep/.el-textarea__inner::placeholder {
                color: #555555;
              }

              /* 设置滚动条的样式 */
              ::-webkit-scrollbar {
                width: 6px;
                border-radius: 3px;
                display: none;
              }
              /* 滚动槽 */
              ::-webkit-scrollbar-track {
                border-radius: 10px;
              }
              /* 滚动条滑块 */
              ::-webkit-scrollbar-thumb {
                border-radius: 10px;
                background: #a0a0a0;
                height: 105px;
              }
            }

            .limit {
              position: absolute;
              left: 530px;
              bottom: 15px;
              font-size: 12px;
              font-family: PingFangSC-Regular, PingFang SC;
              font-weight: 400;
              line-height: 12px;
              color: #999999;

              .limitOut {
                color: #f24038;
              }
              .limitIn {
                color: #00ffb0;
              }
            }
          }
        }

        // submit
        .submitBtn {
          width: 215px;
          height: 39px;
          font-size: 14px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          color: #1e2020;
          line-height: 14px;
          background: none;
          border: none;
          margin: 40px 0 0 90px;
          background: url("../../assets/images/pc_black/home/btn_color.png");
          background-position: center center;
          background-size: 100% 100%;
          border-radius: 0 !important;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  #personalModify {
    position: absolute;
    top: 90px;
    bottom: 0;
    left: 0;
    right: 0;

    // 隐藏pc
    .wrapper {
      display: none;
    }
    // 显示mobile
    .mContainer {
      width: 100%;
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
      // padding-top: 30px;

      // 外容器ul
      .mContainerUl {
        width: 100%;
        padding-left: 30px;

        // 头像样式
        .avatarUpload {
          position: relative;
          height: 85px !important;
          width: 85px !important;
          // border-radius: 50%;
          z-index: 999;

          /deep/.image-circle .image-container {
            height: 85px;
            width: 85px;
            transform: translateY(11px);
            img {
              height: 100%;
              width: 100%;
              opacity: 0;
            }
          }

          /deep/.md-button.md-round,
          .md-button.md-round.md-fab,
          .md-button.md-round.md-just-icon {
            position: absolute;
            top: -60px;
            height: 85px !important;
            width: 85px !important;
            border-radius: 50%;
            opacity: 0;
          }
        }

        .m_showAvatar_box {
          position: relative;

          /deep/.md-field,
          /deep/.md-input {
            // position: absolute;
            margin: 0;
            padding: 0;
            height: 85px !important;
            width: 85px !important;
            border-radius: 50%;
            opacity: 0;
            cursor: pointer;
            z-index: 999;
          }
          /deep/.md-field:before,
          /deep/.md-field:after {
            display: none;
          }
        }
        .m_showAvatar {
          position: absolute;
          top: 50%;
          right: 0;
          transform: translateY(-50%);
          height: 85px;
          width: 85px;
          border-radius: 50%;
        }

        // 每一个li
        li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 100%;
          height: 104px;
          box-shadow: 0px 2px 0px 0px #333333;
          padding-right: 30px;

          // li里面的所有span统一样式
          span {
            font-size: 30px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #ffffff;
            line-height: 40px;
          }

          // 已认证字体颜色
          .certified {
            color: #00ffb0 !important;
          }
        }

        // 昵称的名字字体颜色
        li:nth-child(1) {
          height: 140px;
        }

        li:nth-child(3) {
          span:nth-child(2) {
            max-width: 50%;
            color: #ffffff;
            display: -webkit-box; /**对象作为伸缩盒子模型展示**/
            -webkit-box-orient: vertical; /**设置或检索伸缩盒子对象的子元素的排列方式**/
            -webkit-line-clamp: 1; /**显示的行数**/
            word-break: break-all;
            overflow: hidden; /**隐藏超出的内容**/
          }
        }

        li:nth-child(4) {
          .forthRight {
            display: flex;

            img {
              width: 30px;
              height: 30px;
            }

            span {
              color: #999999;
              margin-left: 12px;
            }
          }
        }
      }

      // 退出按钮
      .exitLoginBox {
        position: absolute;
        bottom: 64px;
        width: 100%;
        padding: 0 30px;
        z-index: 99;

        .exitLogin {
          width: 100%;
          height: 72px;
          font-size: 28px;
          font-family: PingFangSC-Semibold, PingFang SC;
          font-weight: 600;
          border-radius: 0;
          color: #2b2c2d;
          border: none;
          background: none;
          background-position: center center;
          background-size: 100% 100%;
        }
        .btn_grey {
          background-image: url("../../assets/images/mobile_black/home/btn_grey.png");
        }
      }
    }

    // >> 退出弹窗
    /deep/.van-dialog {
      width: 490px;
      height: 300px;
      background: none;
      z-index: 999999;
    }
    /deep/.van-dialog__content {
      display: flex;
      flex-direction: column;
      background: #1e2020;
      height: 220px;
      text-align: center;
      padding: 0 30px;

      span {
        font-size: 25px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: rgba(255, 255, 255, 0.6);
        margin-top: 45px;
      }
      span:nth-child(1) {
        font-size: 30px;
        font-weight: 600;
        color: #ffffff;
      }
      span:nth-child(2) {
        margin-top: 30px;
      }
    }
    /deep/.van-dialog__footer {
      background: #1e2020;
      font-size: 30px;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #ffffff;

      button {
        background: #1e2020;
        font-size: 30px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 600;
        color: #ffffff;
        height: 80px;
      }

      button:nth-child(1) {
        color: rgba(255, 255, 255, 0.6);
      }
    }
  }
}
</style>
